package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Override
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    @Override
    public void add(Member member) {
        String password = member.getPassword();
        if (password != null) {
            //使用md5明文加密
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        memberDao.add(member);
    }

    //根据月份查询会员数量
    @Override
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> memberCount = new ArrayList<>();
        for (String month : months) {
            String date = month + ".31";
            Integer count = memberDao.findMemberCountBeforeDate(date);
            memberCount.add(count);
        }
        return memberCount;
    }

    /**
     * 查询指定日期区间 会员统计
     * @param map
     * @return
     * @throws Exception
     */
    public Map findMemberReportDate(Map map) throws Exception {
        Map map1 = new HashMap<>();//组装数据模型
        String startTime = (String) map.get("startTime");
        String endTime = (String) map.get("endTime");
        List<String> list = DateUtils.getMonthBetween(startTime, endTime, "yyyy-MM");
        if (list.size()>1){
            startTime = list.get(0) + "-31";
            Integer count = memberDao.findMemberCountBeforeDate(startTime);
            ArrayList<String> months = new ArrayList<>();
            ArrayList<Integer> memberCount = new ArrayList<>();
            for (int i = 1; i < list.size(); i++) {
                months.add(list.get(i));
                endTime = list.get(i)+"-31";
                Integer sum = memberDao.findMemberCountBydate(startTime, endTime)+count;
                memberCount.add(sum);
            }
            map1.put("months",months);
            map1.put("memberCount",memberCount);
        }
        return map1;
    }

    public static void main(String[] args) throws Exception {
        List<String> list = DateUtils.getMonthBetween("2019-12-31T16:00:00.000Z", "2020-06-30T16:00:00.000Z", "yyyy-MM");
        System.out.println(list);
    }

}
